import os

from django import http
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views import View
from alipay import AliPay

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from utils.response_code import RETCODE


class PaySucessView(LoginRequiredMixin, View):
    def get(self, request):
        # 1.接收 查询参数
        params_query_dict = request.GET

        # 2. 类型强制转换---queryDict ---->dict()
        data = params_query_dict.dict()

        # 3. pop('sign')
        singnature = data.pop('sign')

        # 4.支付宝二次校验
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        sucess = alipay.verify(data, singnature)

        if sucess:
            # 5. 获取订单号  支付宝交易号码 --持久化 --表 create()
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')

            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 6. 修改订单的状态---待支付--->待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status = OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
            )

            # 7. 返回响应
            context = {
                'trade_id': trade_id
            }

        else:
            context = {
                'trade_id':"交易失败 支付失败了!"
            }

        return render(request, 'pay_success.html', context)



class PaymentView(LoginRequiredMixin, View):
    def get(self, request, order_id):

        # 1.校验 订单是否存在
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except:
            return http.HttpResponseForbidden('订单无效!')

        # 2. 生成 alipay支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 3. 将必传的参数 进行 加密 拼接 url
        order_str = alipay.api_alipay_trade_page_pay(
            subject="美多商城%s" % order_id,
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 4.返回给前端
        alipay_url = settings.ALIPAY_URL + "?" + order_str

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})
